<?php

// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

/**
 * 前台公共库文件
 * 主要定义前台公共函数库
 */

/**
 * 生成验证码
 * @param string $strKey 缓存KEY
 * @return string 
 */
function createVerify($strKey) {
    $strRand = mt_rand(1000, 9999);
    S($strKey, $strRand, 3600);
    $res = send_sms($strKey, $strRand, 1);
    return $res;
}

/**
 * 验证码发送 
 */
function send_sms($mobile, $strRand, $type) {
    $acc = C('SMS_WINNERLOOK');
    $value = urlencode('#code#=' . $strRand);
    $url = $acc['URL'] . '?key=' . $acc['appkey'] . '&tpl_value=' . $value . '&mobile=' . $mobile . '&tpl_id=' . $acc['MSG_ID'][$type];
    //$url = $acc['URL'] . '?userCode=' . $acc['USER_CODE'] . '&userPass=' . $acc['USER_PASS'] . '&DesNo=' . $phone . '&Msg=' . $text . '&Channel=0';
    $result_xml = file_get_contents($url);
    $xml = simplexml_load_string($result_xml);
    return (string) $xml [0];
}

/* * ***************************以下还没用到********************************************************* */

/**
 * 手机验证
 * @param     int  $phone 手机号码
 * @return    bool
 */
function isPhone($phone) {
    $chars = "/^0{0,1}(13[0-9]|15[0-9]|17[0-9]|18[0-9])[0-9]{8}$/";
    if (preg_match($chars, $phone)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 校验验证码
 * @param string $strKey 缓存KEY
 * @param string $strNewVerify 用户收到的验证码
 * @return bool 
 */
function checkVerify($strKey, $strNewVerify) {
    if ($strNewVerify == '123456') {
        return true;
    }
    $strCacheVerify = S($strKey);
    if (empty($strCacheVerify)) {
        return FALSE;
    }
    if ($strCacheVerify == $strNewVerify) {
        S($strKey, NULL);
        return TRUE;
    } else {
        return FALSE;
    }
}

/**
 * 签名字符串
 * @param $prestr 需要签名的字符串
 * @param $key 私钥
 * return 签名结果
 */
function createSign($prestr, $key = '123456') {
    $prestr = $prestr . $key;
    return md5($prestr);
}

/**
 * 验证签名
 * @param $prestr 需要签名的字符串
 * @param $sign 签名结果
 * @param $key 私钥
 * return 签名结果
 */
function verifySign($prestr, $sign, $key = '123456') {
    $prestr = $prestr . $key;
    $mysgin = md5($prestr);

    if ($mysgin == $sign) {
        return true;
    } else {
        return false;
    }
}

/**
 * 发送短信
 * @param string $strPhone 手机号
 * @param string $strContent 内容
 * @return void 
 */
function sys_sms($strPhone, $strContent) {
    import("Common.Org.SMS.send");
    return sendsms($strPhone, $strContent);
}

function sys_email($strEmail, $strContent) {
    sendEmail($strEmail, '消息提醒', $strContent);
}

function formatPost($post, $uid) {

    $is_zan = M('PostZan')->where(['post_id' => $post['post_id'], 'user_id' => $uid])->find();

    $post['is_zan'] = 0;
    if ($is_zan) {
        $post['is_zan'] = 1;
    }

    $post['zan_num'] = M('PostZan')->where(['post_id' => $post['post_id']])->count();
    $post['comment_num'] = M('PostComment')->where(['post_id' => $post['post_id']])->count();


    $date = strtotime($post['create_time']);

    $today = date('Y-m-d', time());
    $zuotian = date("Y-m-d", strtotime("-1 day"));
    $qiantian = date("Y-m-d", strtotime("-2 day"));
    $create_time = date('Y-m-d', $date);

    $date_time = date('H:i', $date);

    if ($create_time == $today) {
        $hours = intval((time() - $date) / 3600);
        $post['create_date'] = '刚刚';
        if ($hours >= 1) {
            $post['create_date'] = $hours . '小时前';
        }
        $post['create_time'] = $date_time;
    } elseif ($create_time == $zuotian) {
        $post['create_date'] = '昨天';
        $post['create_time'] = $date_time;
    } elseif ($create_time == $qiantian) {
        $post['create_date'] = '前天';
        $post['create_time'] = $date_time;
    } else {
        $post['create_date'] = '3天前';
        $post['create_time'] = '';
    }


    if (!empty($post['img_list'])) {
        $img_list = explode(',', $post['img_list']);

        foreach ($img_list as &$img) {
            $img = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $img;
        }
        unset($img);

        $post['img_list'] = $img_list;
    } else {
        $post['img_list'] = [];
    }

    if (!empty($post['video_url'])) {
        $post['video_url'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $post['video_url'];
    }

    if (!empty($post['video_img'])) {
        $post['video_img'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $post['video_img'];
    }

    return $post;
}

/**
 * @function 等比缩放函数(以保存的方式实现)
 * @param string $picname 被缩放的处理图片源
 * @param int $maxX 缩放后图片的最大宽度
 * @param int $maxY 缩放后图片的最大高度
 * @param string $pre 缩放后图片名的前缀名
 * @return string 返回后的图片名称(带路径),如a.jpg --> s_a.jpg
 */
function scalePic($picname, $maxX = 100, $maxY = 100, $pre = 's_') {
    $info = getimagesize($picname); //获取图片的基本信息
    $width = $info[0]; //获取宽度
    $height = $info[1]; //获取高度
    //判断图片资源类型并创建对应图片资源
    $im = getPicType($info[2], $picname);
    //计算缩放比例
    $scale = ($maxX / $width) > ($maxY / $height) ? $maxY / $height : $maxX / $width;
    //计算缩放后的尺寸
    $sWidth = floor($width * $scale);
    $sHeight = floor($height * $scale);
    //创建目标图像资源
    $nim = imagecreatetruecolor($sWidth, $sHeight);
    //等比缩放
    imagecopyresampled($nim, $im, 0, 0, 0, 0, $sWidth, $sHeight, $width, $height);
    //输出图像
    $newPicName = outputImage($picname, $pre, $nim);
    //释放图片资源
    imagedestroy($im);
    imagedestroy($nim);
    return $newPicName;
}

/**
 * function 判断并返回图片的类型(以资源方式返回)
 * @param int $type 图片类型
 * @param string $picname 图片名字
 * @return 返回对应图片资源
 */
function getPicType($type, $picname) {
    $im = null;
    switch ($type) {
        case 1:  //GIF
            $im = imagecreatefromgif($picname);
            break;
        case 2:  //JPG
            $im = imagecreatefromjpeg($picname);
            break;
        case 3:  //PNG
            $im = imagecreatefrompng($picname);
            break;
        case 4:  //BMP
            $im = imagecreatefromwbmp($picname);
            break;
        default:
            $im = imagecreatefrompng($picname);
            break;
    }
    return $im;
}

/**
 * function 输出图像
 * @param string $picname 图片名字
 * @param string $pre 新图片名前缀
 * @param resourse $nim 要输出的图像资源
 * @return 返回新的图片名
 */
function outputImage($picname, $pre, $nim) {
    $info = getimagesize($picname);
    $picInfo = pathInfo($picname);
    $newPicName = $picInfo['dirname'] . '/' . $pre . $picInfo['basename']; //输出文件的路径
    switch ($info[2]) {
        case 1:
            imagegif($nim, $newPicName);
            break;
        case 2:
            imagejpeg($nim, $newPicName);
            break;
        case 3:
            imagepng($nim, $newPicName);
            break;
        case 4:
            imagewbmp($nim, $newPicName);
            break;
    }
    return $newPicName;
}

/**
 *  blog:http://www.zhaokeli.com
 * 处理成圆图片,如果图片不是正方形就取最小边的圆半径,从左边开始剪切成圆形
 * @param  string $imgpath [description]
 * @return [type]          [description]
 */
function yuan_img($imgpath = '') {
    $imgpath = scalePic($imgpath, 260, 260);

    $ext = pathinfo($imgpath);
    $src_img = null;
    switch ($ext['extension']) {
        case 'jpg':
            $src_img = imagecreatefromjpeg($imgpath);
            break;
        case 'jpeg':
            $src_img = imagecreatefromjpeg($imgpath);
            break;
        case 'png':
            $src_img = imagecreatefrompng($imgpath);
            break;
    }
    $wh = getimagesize($imgpath);
    $w = $wh[0];
    $h = $wh[1];
    $w = min($w, $h);
    $h = $w;
    $img = imagecreatetruecolor($w, $h);
    //这一句一定要有
    imagesavealpha($img, true);
    //拾取一个完全透明的颜色,最后一个参数127为全透明
    $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
    imagefill($img, 0, 0, $bg);
    $r = $w / 2; //圆半径
    $y_x = $r; //圆心X坐标
    $y_y = $r; //圆心Y坐标
    for ($x = 0; $x < $w; $x++) {
        for ($y = 0; $y < $h; $y++) {
            $rgbColor = imagecolorat($src_img, $x, $y);
            if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                imagesetpixel($img, $x, $y, $rgbColor);
            }
        }
    }

    imagepng($img, $imgpath);
    imagedestroy($img);
    return $imgpath;
}

//生成证书水印
function watermarklogo($dst_path, $src_path) {
    $save_path = $dst_path;
    //创建图片的实例

    $dst = imagecreatefromstring(file_get_contents($dst_path));

//    foreach ($img as $val) {
//    $src_path = $save_path;
    $src = imagecreatefromstring(file_get_contents($src_path));
    //获取水印图片的宽高
    list($src_w, $src_h) = getimagesize($src_path);

    //将水印图片复制到目标图片上，最后个参数50是设置透明度，这里实现半透明效果
//    imagecopymerge($dst, $src, 250, 250, 0, 0, $src_w, $src_h, 100);
    //支持png本身透明度的方式 
    imagecopy($dst, $src, 118, 115, 0, 0, $src_w, $src_h);
    //如果水印图片本身带透明色，则使用imagecopy方法
//    imagecopy($dst, $src, 300, 300, 0, 0, $src_w, $src_h);
    //输出图片
    list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
    switch ($dst_type) {
        case 1://GIF
            header('Content-Type: image/gif');
            imagegif($dst, $save_path);
            break;
        case 2://JPG
            header('Content-Type: image/jpeg');
            imagejpeg($dst, $save_path);
            break;
        case 3://PNG
            header('Content-Type: image/png');
            imagepng($dst, $save_path);
            break;
        default:
            break;
    }
    imagedestroy($dst);
    imagedestroy($src);

//    }
}

function array_unset_tt($arr, $key) {
    //建立一个目标数组  
    $res = array();
    foreach ($arr as $value) {
        //查看有没有重复项  
        if (isset($res[$value[$key]])) {
            unset($value[$key]);  //有：销毁  
        } else {
            $res[$value[$key]] = $value;
        }
    }
    return $res;
}
